package com.opNaga.bpmp.swimlane;

import com.opNaga.bpmp.BPMPElement;
import com.opNaga.bpmp.flowObject.event.EndEvent;
import com.opNaga.bpmp.flowObject.event.StartEvent;

/**
 * User: Junyi BEI
 * Date: 19/01/2012
 * Time: 13:53
 */
public class Lane extends Swimlane {
  private BPMPElement parent;

  public Lane() {
    super();
  }

  public Lane(String t) {
    super(t);
  }

  @Override
  public String getType() {
    return "Lane";
  }

  @Override
  public boolean destroy() {
    if(!((Pool) parent).removeLane(this)) {
      return standardMessage(850, parent);
    }
    return super.destroy();
  }

  public boolean addElement(BPMPElement be) {
    if(!(be instanceof Containable)) {
      return standardMessage(550, be);
    }
    if(!((Containable) be).setContainer(this)) {
      return standardMessage(551, be);
    }
    if(be instanceof StartEvent) {
      if(!((Pool) parent).registerStart(be)) {
        return standardMessage(553, be);
      }
    }
    if(be instanceof EndEvent) {
      if(!((Pool) parent).registerEnd(be)) {
        return standardMessage(554, be);
      }
    }
    if(!elements.add(be)) {
      return standardMessage(552, be);
    }
    return standardMessage(590, be);
  }

  public boolean removeElement(BPMPElement be) {
    if(!(be instanceof Containable)) {
      return standardMessage(560, be);
    }
    if(!((Containable) be).setContainer(null)) {
      return standardMessage(561, be);
    }
    if(be instanceof StartEvent) {
      if(!((Pool) parent).deregisterStart(be)) {
        return standardMessage(563, be);
      }
    }
    if(be instanceof EndEvent) {
      if(!((Pool) parent).deregisterEnd(be)) {
        return standardMessage(564, be);
      }
    }
    if(!elements.remove(be)) {
      return standardMessage(562, be);
    }
    return standardMessage(591, be);
  }

  public BPMPElement getRoot() {
    return ((Pool) parent).getRoot();
  }

  public BPMPElement getParent() {
    return parent;
  }

  public boolean isRoot() {
    return false;
  }

  public boolean setParent(BPMPElement be) {
    if(be == null) {
      parent = be;
      return true;
    }
    if(!Pool.class.isAssignableFrom(be.getClass())) {
      return standardMessage(520, be);
    }
    if(parent != null) {
      return standardMessage(521, be, parent);
    }
    parent = be;
    return standardMessage(542, be);
  }
}
